<?php

namespace app\api\controller\v46;

use app\api\controller\v13\Auth2;
use app\common\cachemodel\zlcr2\Zlcr2QuestionUserView;
use app\common\cachemodel\zlcr2\Zlcr2UserQuestion;
use app\common\cachemodel\zlcr3\Zlcr3ConsultAccount;
use app\common\cachemodel\zlcr3\Zlcr3Follow;
use app\common\cachemodel\ZlcrAstr;
use app\common\lib\Util;
use app\zyhsapi\model\good_rtc_live\ZyhsGoodRtcLiveMedia;
use app\zyhsapi\model\good_rtc_live\ZyhsGoodRtcLiveRecord;
use app\zyhsapi\model\ZyhsConfig;
use app\zyhsapi\model\ZyhsConsultAstrData;
use app\zyhsapi\model\ZyhsConsultChatRecord;
use app\zyhsapi\model\ZyhsConsultChatRecordDetails;
use app\zyhsapi\model\ZyhsConsultChatRtcRecordComment;
use app\zyhsapi\model\ZyhsConsultRtcUserBenefits;
use app\zyhsapi\model\ZyhsTag;
use think\Cache;
use think\Config;
use think\response\Json;

class ConsultChat extends Auth2
{
    private $appType2 = 2;

    /**
     * 连线咨询 首页
     * @return Json
     * @throws \Exception
     */
    public function index()
    {
        $zoneList = Config::Load(APP_PATH . 'zyhsapi/extra/consult_zone.php', 'consult_zone', 'zyhs');;
        $zoneListTmp = [
            [
                'title' => '关注',
                'type' => -1,
            ],
        ];
        foreach ($zoneList as $zone)
        {
            if ($zone['status'])
            {
                if ($zone['type'] === 5 && Util::IsHuaweiOrHonor())//华为渠道不展示婚姻关系专区
                {

                } else
                {
                    $zoneListTmp[] = [
                        'title' => $zone['name'],
                        'type' => $zone['type'],
                    ];
                }
            }
        }

        if (!Util::AppIsPassShowV1())
        {
            $zyhsGoodRtcLiveRecordModel = new ZyhsGoodRtcLiveRecord();
            $liveRecordId = $zyhsGoodRtcLiveRecordModel->getNewestRecordId($this->appType2);
            if ($liveRecordId)
            {   // 直播记录详情
                $recordInfo = $zyhsGoodRtcLiveRecordModel->getInfoById($liveRecordId);
                if ($recordInfo)
                {   // 获取 直播录音资源信息
                    $mediaInfo = (new ZyhsGoodRtcLiveMedia())->getInfoById($recordInfo['current_mid']);
                    $astrInfo = (new ZlcrAstr())->getInfoById($mediaInfo['astr_id'], ['avatar', 'nickname']);

                    $goodRtc = [
                        'img' => '/zyhsapp/good_rtc/zhunle_recommend_img.png',
                        'live_avatar' => $astrInfo['avatar'],
                        'live_name' => $astrInfo['nickname'],
                        'desc' => '播放中',
                        'user_avatar' => $mediaInfo['avatar'],
                        'user_name' => $mediaInfo['nickname'],
                        'tip_url' => '/zyhsapp/good_rtc/good_rtc_tip.png',
                        'target' => 'local',
                        'link' => 'live_official_detail_page?need_auth=0',
                    ];
                }
            }
        }
        $consultData = [
            'img' => '/test/consult_chat/consult_tip_img.png',
            'title' => '咨询消息',
            'desc' => '暂无任何消息',
            'new_msg' => 0,
        ];
        $popWindows = null;
        $newMsg = 0;
        if ($this->user)
        {
            // 连线咨询 ---------
            $consultChatRecordModel = new ZyhsConsultChatRecord();
            $consultChatRecordModel->setPageAndLimit(1, 1);
            $pageData = $consultChatRecordModel->getListPage($this->user['id'], 'last_chat_detail_time', [], $this->appType2, 'desc', 0);
            $pageData['data'] = $consultChatRecordModel->dataInit($pageData['data']);
            $dataItem = $pageData['data'] ? current($pageData['data']) : [];
            if ($dataItem)
            {
                $astrInfo = (new ZlcrAstr())->getInfoById($dataItem['astr_id'], ['nickname']);
                $chatDetail = (new ZyhsConsultChatRecordDetails())->getInfoById($dataItem['last_chat_detail_id'], ['content', 'data_type', 'extend']);
                switch ($chatDetail['data_type'])
                {
                    case 1:
                    case 4:
                        $content = $chatDetail['content'];
                        break;
                    case 2:
                        $content = '[图片]';
                        break;
                    case 3:
                        $content = '[语音连线]';
                        break;
                    case 5:
                        $content = '收到问题回复';
                        break;
                    case 6:
                    case 7:
                        $content = '[悬赏问答] 你好，你的疑惑已给出回复，点击下方即可查看，有什么问题可以追问我继续帮你进行解答～';
                        break;
                    case 8:
                        $content = '[星盘]';
                        break;
                    case 9:
                        $content = '[预约]';
                        break;
                    default:
                        $content = '';
                }
                $consultData['desc'] = "{$astrInfo['nickname']}：{$content}";
                $consultData['new_msg'] = $consultChatRecordModel->getUserUnreadAllNum($this->appType2, $this->user['id']); // 未读消息数量
                if ($consultData['new_msg'] > 99)
                {
                    $consultData['new_msg'] = 99;
                }
            }
            //  服务 小红点------
            do
            {   // 未读 消息数量
                if ((new Zlcr2UserQuestion())->getUserUnReadIds($this->user['id']))
                {   // 未读问题ids
                    $newMsg = 1;
                    break;
                }
                if ((new Zlcr2QuestionUserView())->getUserUnReadViewIds($this->user['id']))
                {   // 未读蹭看ids
                    $newMsg = 1;
                    break;
                }
            } while (false);
            //  弹窗 ---------
            $benefitsCacheKey = 'reg_user_send_benefits_' . date('Ymd') . ':' . $this->user['id'];
            if (!Cache::get($benefitsCacheKey, false))
            {
                Cache::set($benefitsCacheKey, 1, 86400);    // 今日已经 弹了提示 不再弹了
                // 获取 用户 当前的福利信息
                $zyhsConsultRtcUserBenefitsModel = new ZyhsConsultRtcUserBenefits();
                $newUserWelfare = $zyhsConsultRtcUserBenefitsModel->getConsultRtcUserBenefits($this->appType2, $this->user['id']);
                if ($newUserWelfare && isset($newUserWelfare['min']) && $newUserWelfare['min'])
                {
                    $expireTime = $this->request->time() + 259200;  // 3天后
                    if (isset($newUserWelfare['type']) && $newUserWelfare['type'] === 2 && $newUserWelfare['expire_time'] > $expireTime)
                    {   // 脚本 赠送   并且 过期时间 大于 3天 ，强制更新过期时间 为3天后
                        $zyhsConsultRtcUserBenefitsModel->updateData($newUserWelfare['id'], $this->appType2, $this->user['id'], ['expire_time' => $expireTime]);
                    }
                    $popWindows = Util::getZhunleConsultBenefitsConfig($newUserWelfare['min']);
                }
            }
        }
        $resData = [
            'new_msg' => $newMsg,
            'consult_data' => $consultData,
            'good_rtc' => $goodRtc ?? null,
            'selected_zone_tab_index' => 1,
            'zone_tab' => $zoneListTmp,
            'pop_windows' => $popWindows,
            'gift_pack_is_show' => 1,
        ];

        return show(config('code.success'), '请求成功', $resData);
    }

    public function getNewMsgData()
    {
        $consultData = [
            'img' => '/test/consult_chat/consult_tip_img.png',
            'title' => '咨询消息',
            'desc' => '暂无任何消息',
            'new_msg' => 0,
        ];
        $newMsg = 0;
        if ($this->user)
        {
            // 连线咨询 ---------
            $consultChatRecordModel = new ZyhsConsultChatRecord();
            $consultChatRecordModel->setPageAndLimit(1, 1);
            $pageData = $consultChatRecordModel->getListPage($this->user['id'], 'last_chat_detail_time', [], $this->appType2, 'desc', 0);
            $pageData['data'] = $consultChatRecordModel->dataInit($pageData['data']);
            $dataItem = $pageData['data'] ? current($pageData['data']) : [];
            if ($dataItem)
            {
                $astrInfo = (new ZlcrAstr())->getInfoById($dataItem['astr_id'], ['nickname']);
                $chatDetail = (new ZyhsConsultChatRecordDetails())->getInfoById($dataItem['last_chat_detail_id'], ['content', 'data_type', 'extend']);
                switch ($chatDetail['data_type'])
                {
                    case 1:
                    case 4:
                        $content = $chatDetail['content'];
                        break;
                    case 2:
                        $content = '[图片]';
                        break;
                    case 3:
                        $content = '[语音连线]';
                        break;
                    case 5:
                        $content = '收到问题回复';
                        break;
                    case 6:
                    case 7:
                        $content = '[悬赏问答] 你好，你的疑惑已给出回复，点击下方即可查看，有什么问题可以追问我继续帮你进行解答～';
                        break;
                    case 8:
                        $content = '[星盘]';
                        break;
                    default:
                        $content = '';
                }
                $consultData['desc'] = "{$astrInfo['nickname']}：{$content}";
                $consultData['new_msg'] = $consultChatRecordModel->getUserUnreadAllNum($this->appType2, $this->user['id']); // 未读消息数量
            }
            //  服务 小红点------
            do
            {   // 未读 消息数量
                if ((new Zlcr2UserQuestion())->getUserUnReadIds($this->user['id']))
                {   // 未读问题ids
                    $newMsg = 1;
                    break;
                }
                if ((new Zlcr2QuestionUserView())->getUserUnReadViewIds($this->user['id']))
                {   // 未读蹭看ids
                    $newMsg = 1;
                    break;
                }
            } while (false);
        }

        $resData = [
            'new_msg' => $newMsg,
            'consult_data' => $consultData,
        ];

        return show(config('code.success'), '请求成功', $resData);
    }

    /**
     * 专区咨询师列表
     * @return Json
     * @throws \Exception
     */
    public function getConsultAstrList()
    {
        $type = input('type/d', 0);
        $page = input('page/d', 1);
        $zoneConfig = Config::Load(APP_PATH . 'zyhsapi/extra/consult_zone.php', 'consult_zone', 'zyhs');;
        $zoneTypes = array_column($zoneConfig, 'type');
        // if (!in_array($type, $zoneTypes, true))
        // {
        //     return show(config('code.error'), '未知的专区');
        // }
        // 获取 占星师 热的信息
        $astrHotData = (new ZyhsConsultAstrData())->getRankingList(2);
        //获取当前专区的咨询师列表
        $consultModel = new Zlcr3ConsultAccount();
        $zyhsRtcConfig = (new ZyhsConfig())->configInfo('rtc');
        if (Util::ZyhsIsHuaweiOrHonorOrOppoHg(2))
        {   // 华为 合规情况 只显示 当前占星师数据
            if (Util::IsHuaweiAndOppo())
            {
                $astrIdList = $zyhsRtcConfig['huawei_hg_consult_astr_ids'] ? explode(',', $zyhsRtcConfig['huawei_hg_consult_astr_ids']) : [];
            } else
            {
                $astrIdList = $zyhsRtcConfig['honor_hg_consult_astr_ids'] ? explode(',', $zyhsRtcConfig['honor_hg_consult_astr_ids']) : [];
            }
            $total = count($astrIdList);
            $pageData = [
                'total' => $total,// 记录总数
                'per_page' => 100000,// 每页多少条
                'current_page' => 1,// 当前页数
                'last_page' => 1,// 总页数
                'data' => [],
            ];

            foreach ($astrIdList as $astrIdItem)
            {
                if (!isset($astrHotData[$astrIdItem]))
                {
                    $astrHotData[$astrIdItem] = 0;
                }
                $pageData['data'][] = (int)$astrIdItem;
            }
        } else
        {
            $pageData = $consultModel->getChatConsultIds(0, $page, 100000);
        }
        // 过滤 测试咨询师
        $testAstrIds = isset($zyhsRtcConfig['consult_test_astr_id']) && $zyhsRtcConfig['consult_test_astr_id'] ? explode(',', $zyhsRtcConfig['consult_test_astr_id']) : [];
        $testAstrIds = array_map('intval', $testAstrIds);
        $astrIdsLimit = [];
        foreach ($pageData['data'] as $astrIdItem)
        {
            if (!in_array($astrIdItem, $testAstrIds, true))
            {
                $astrIdsLimit[] = $astrIdItem;
            }
        }
        //获取分页后的数据
        $astrConsultInfos = $consultModel->batchGetInfoByIds($astrIdsLimit, ['service_duration', 'recommended_nums', 'status', 'tids', 'tags', 'level']);
        $astrInfo = (new ZlcrAstr())->batchGetInfoByIds($astrIdsLimit);
        $astrList1 = [];
        $astrList2 = [];
        $workIntro = "";
        if (Util::ZyhsIsHuaweiOrHonorOrOppoHg(2))
        {
            if (Util::IsHuaweiAndOppo())
            {
                if (isset($zyhsRtcConfig['huawei_work_intro']) && $zyhsRtcConfig['huawei_work_intro'])
                {
                    $workIntro = $zyhsRtcConfig['huawei_work_intro'];
                }
            } else
            {
                if (isset($zyhsRtcConfig['honor_work_intro']) && $zyhsRtcConfig['honor_work_intro'])
                {
                    $workIntro = $zyhsRtcConfig['honor_work_intro'];
                }
            }
        }
        // 获取新人福利 免充值 发起连线
        $newUserWelfare = $this->user ? (new ZyhsConsultRtcUserBenefits())->getConsultRtcUserBenefits($this->appType2, $this->user['id']) : null;
        $freeRtcDuration = $newUserWelfare ? (($newUserWelfare['min'] ?? 0) * 60) : 0;
        // 免费 连线 时长
        $freeConsultDuration = $freeRtcDuration > 0 ? 1 : 0;
        if ($freeConsultDuration > 0)
        {
            $consultBtnName = sprintf("免费咨询%d分钟", (int)($freeRtcDuration / 60));
        } else
        {
            $consultBtnName = '连线咨询';
        }
        foreach ($astrHotData as $astrId => $s)
        {   // 热度榜遍历
            if (!isset($astrConsultInfos[$astrId]))
            {
                continue;
            }
            $item = $astrConsultInfos[$astrId];
            $tips = '';
            if ($item['service_duration'])
            {
                $i = ceil($item['service_duration'] / 60);
                $tips .= '服务' . ($i > 2000 ? '2000+' : $i) . '分钟';
            }
            if ($item['recommended_nums'])
            {
                if ($tips)
                {
                    $tips .= '·';
                }
                $tips .= $item['recommended_nums'] . "次被推荐";
            }
            $tags = $consultModel->getTags($item['tags']);
            if (Util::ZyhsIsHuaweiOrHonorOrOppoHg(2))
            {
                $tags = array_values(array_diff($tags, ['星盘']));
            }
            if ($item['status'] == 1)
            {   // 在线
                $astrList1[] = [
                    'name' => $astrInfo[$astrId]['nickname'],
                    'avatar' => $astrInfo[$astrId]['avatar'],
                    'tags_icon' => $consultModel->getTagsIcon($item['tids']),
                    'tags' => $tags,
                    'des' => $workIntro ?: $astrInfo[$astrId]['work_intro'],
                    'status' => 1,
                    'id' => $astrId,
                    'tips' => $tips,
                    'level' => $item['level'],
                    'btn_data' => [['title' => '预沟通', 'type' => 1,], ['title' => $consultBtnName, 'type' => 2,],],
                ];
            } else
            {   // 休息
                $astrList2[] = [
                    'name' => $astrInfo[$astrId]['nickname'],
                    'avatar' => $astrInfo[$astrId]['avatar'],
                    'tags_icon' => $consultModel->getTagsIcon($item['tids']),
                    'tags' => $tags,
                    'des' => $workIntro ?: $astrInfo[$astrId]['work_intro'],
                    'status' => 2,
                    'id' => $astrId,
                    'tips' => $tips,
                    'level' => $item['level'],
                    'btn_data' => [['title' => '预沟通', 'type' => 1,],],
                ];
            }
        }
        $pageData['data'] = array_merge($astrList1, $astrList2);
        return show(config('code.success'), 'Success.', $pageData);
    }

    /**
     * 获取提问占星师列表
     * @return Json
     * @throws \Exception
     */
    public function getSendQuestionAstrList()
    {
        $num = input('num/d', 5);

        $resData = [];
        if ($num)
        {
            //获取当前专区的咨询师列表
            $consultModel = new Zlcr3ConsultAccount();
            $pageData = $consultModel->getChatConsultIds(0, -1, 100000);
            if ($pageData['data'])
            {
                $testAccountConfig = (new ZyhsConfig())->configInfo('rtc');
                $testUser = $testAccountConfig['test_user'] ?? '';
                $testAstrId = $testUser ? explode(',', $testUser) : [];
                $testAstrId = array_map('intval', $testAstrId);
                $idList = [];
                foreach ($pageData['data'] as $value)
                {
                    if (!in_array($value, $testAstrId, true))
                    {
                        $idList[] = $value;
                    }
                }
                $astrList = $consultModel->batchGetInfoByIds($idList, ['status', 'consult_status']);
                $astrIds1 = [];
                $astrIds2 = [];
                foreach ($astrList as $astrId => $dataItem)
                {
                    if ($dataItem['consult_status'] === 1)
                    {
                        if ($dataItem['status'] === 1)
                        {   // 在线咨询师
                            $astrIds1[] = $astrId;
                        } else
                        {   // 离线咨询师
                            $astrIds2[] = $astrId;
                        }
                    }
                }
                shuffle($astrIds1);
                shuffle($astrIds2);
                if (count($astrIds1) + count($astrIds2) <= $num)
                {
                    $resIds = array_merge($astrIds1, $astrIds2);
                } else
                {
                    if (count($astrIds1) >= $num)
                    {
                        $resIds = array_slice($astrIds1, 0, $num);
                    } else
                    {
                        $resIds = $astrIds1;
                    }
                    $n = count($resIds);
                    if ($n < $num)
                    {   // 占星师 不足需要占星师数
                        $resIds1 = array_slice($astrIds2, 0, $num - $n);
                        $resIds = array_merge($resIds, $resIds1);
                    }
                }

                $astrInfoList = (new ZlcrAstr())->batchGetInfoByIds($resIds, ['id', 'avatar', 'nickname']);
                foreach ($resIds as $astrId)
                {
                    if (isset($astrInfoList[$astrId]) && $astrInfoList[$astrId])
                    {
                        $astrInfoList[$astrId]['id'] = (int)$astrInfoList[$astrId]['id'];
                        $resData[] = $astrInfoList[$astrId];
                    }
                }
            }
        }

        return show(config('code.success'), '请求成功', $resData);
    }

    /**
     * 咨询师主页
     * @return Json
     * @throws \Exception
     */
    public function homePage()
    {
        $astrId = input('astr_id/d', 0);
        $zlcrAstrModel = new ZlcrAstr();
        $astrInfo = $zlcrAstrModel->getInfoById($astrId);
        if (!$astrInfo)
        {
            return show(config('code.error'), '咨询师不存在');
        }
        $res = $zlcrAstrModel->homePage($astrInfo, 1, 2);
        if ($this->user)
        {
            $resData = (new Zlcr3Follow())->userFollowInfo($this->user['id'], -1);
            $followIds = array_keys($resData['data']);
            $followIds = $followIds ?: [];
            $newUserWelfare = (new ZyhsConsultRtcUserBenefits())->getConsultRtcUserBenefits($this->appType2, $this->user['id']);
            $res['btn_name'] = $newUserWelfare ? sprintf("免费咨询连线%d分钟", $newUserWelfare['min'] ?? 0) : '现在咨询';
        } else
        {
            $followIds = [];
            $res['btn_name'] = '现在咨询';
        }
        $res['follow_status'] = in_array($astrId, $followIds, false) ? 1 : 2;
        if (Util::ZyhsIsHuaweiOrHonorOrOppoHg(2))
        {
            $res['tags'] = array_values(array_diff($res['tags'], ['星盘']));
        }

        return show(config('code.success'), '', $res);
    }

    /**
     * 占星师评价列表
     * @return Json
     * @throws \Exception
     */
    public function commentList()
    {
        $astrId = input('astr_id/d', 0);
        $list = (new ZyhsConsultChatRtcRecordComment())->astrCommentList($astrId);
        if ($list['data'])
        {
            array_multisort(array_column($list['data'], 'create_time'), SORT_NUMERIC, SORT_DESC, $list['data']);
        }
        $res = [];
        $tagsModel = new ZyhsTag();
        foreach ($list['data'] as $item)
        {
            $tagInfo = $tagsModel->batchGetInfoByIds($item['tids'], ['tag_name']);
            $res[] = [
                'name' => $item['name'] ?: '',
                'avatar' => $item['avatar'] ?: '',
                'time' => date('Y.m.d H:i', $item['create_time']),
                'tags' => array_column($tagInfo, 'tag_name'),
                'score' => $item['level'],
                'content' => $item['comment'],
            ];
        }
        $list['data'] = $res;
        return show(config('code.success'), 'Success.', $list);
    }
}
